﻿using System;
using System.Collections.Generic;
using System.Security.Permissions;

using Moe.ECamel.Common.Contracts;
using Moe.ECamel.Common.Entities;
using Moe.ECamel.Common.Security;
using Moe.ECamel.Server.BL;

namespace Moe.ECamel.Server.Services
{
	/// <summary>
	/// Service Interface for Libraries services.
	/// </summary>
	public class LibraryService : ECamelService, ILibraryService
	{
		public LibraryService()
		{
		}
		public LibraryService(ECamelService caller)
			: base(caller)
		{
		}

		#region ILibraryService Members

		[PrincipalPermission(SecurityAction.Demand, Role = Operations.LibraryView)]
		public Library GetLibraryById(int libraryId)
		{
			// Execute operation via service BL:
			using (var bl = new LibraryBL(GetReadOnlyDataContext()))
			{
				return bl.GetLibraryById(libraryId);
			}
		}

		[PrincipalPermission(SecurityAction.Demand, Role = Operations.LibraryView)]
		public List<Library> GetAllLibraries()
		{
			// Execute operation via service BL:
			using (var bl = new LibraryBL(GetReadOnlyDataContext()))
			{
				return bl.GetAllLibraries();
			}
		}
		
		[PrincipalPermission(SecurityAction.Demand, Role=Operations.LibraryAdd)]
		public ECamelError CreateLibrary(Library library)
		{
			return CreateLibraries(new Library[] {library});
		}
		
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.LibraryAdd)]
		public ECamelError CreateLibraries(IEnumerable<Library> libraries)
		{
			using (var bl = new LibraryBL(GetReadWriteDataContext()))
			{
				foreach (var library in libraries)
				{
					ECamelError error = bl.CreateLibrary(library);
					if (error != null)
						return error;
				}
			}

			return SubmitChanges(null);
		}

		[PrincipalPermission(SecurityAction.Demand, Role = Operations.LibraryEdit )]
		public ECamelError UpdateLibrary(Library library)
		{
			ECamelError error;

			using (var bl = new LibraryBL(GetReadWriteDataContext()))
			{
				error = bl.UpdateLibrary(library);
			}

			return SubmitChanges(error);
		}
		
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.LibraryChangeStatus)]
		public ECamelError UpdateLibraryStatus(int libraryId, bool active)
		{
			using (var bl = new LibraryBL(GetReadWriteDataContext()))
			{
				// Get library:
				var library = bl.GetLibraryById(libraryId);
				// Check if status update is relevant:
				if (library.Active == active)
					return null;
				// Update status:
				library.Active = active;
			}

			SubmitChanges();
			return null;
		}

		#endregion
	}
}